package com.feicheng.lanniao.service.impl;

import com.feicheng.lanniao.entity.Brand;
import com.feicheng.lanniao.exception.SystemException;
import com.feicheng.lanniao.mapper.BrandMapper;
import com.feicheng.lanniao.result.ResultInfo;
import com.feicheng.lanniao.service.IBrandService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author feichengTech
 * @since 2021-09-02
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {

	/**
	 * @see.IBrandService.selectBrandbyId
	 */
	@Override
	public ResultInfo selectBrandbyId(Integer brandId) {
		// TODO Auto-generated method stub
		//根据brandId 查询一条品牌信息
		return ResultInfo.success(this.getById(brandId));
	}

	@Override
	public ResultInfo getBrandInfo(Integer size) {
		// TODO Auto-generated method stub
		//查询所有删除位是true的品牌信息
		QueryWrapper<Brand> queryWrapper = new QueryWrapper<Brand>();
		queryWrapper.eq("del_flag", true);
		//判断size不为空
		if(null != size && 0 != size) {
			queryWrapper.last("limit " + size );
		}
		return ResultInfo.success(this.list(queryWrapper));
	}

	@Override
	public ResultInfo updateBrand(Brand brand) {
		// TODO Auto-generated method stub
		//判断要修改的车辆品牌ID是否为空，为空则抛出异常
		if(null == this.getById(brand.getBrandId())) {
			throw new SystemException("品牌Id缺失，无法更新");
		}
		//车辆品牌ID不为空，则根据车辆品牌ID修改品牌信息
		this.updateById(brand);
		return ResultInfo.success();
	}

	@Override
	public ResultInfo deleteBrand(Integer brandId) {
		// TODO Auto-generated method stub
		//如果ID为空 抛出异常
		if(null == brandId) {
			throw new SystemException("brandId 为空");
		}
		//构建查询条件
		QueryWrapper<Brand> queryWrapper = new QueryWrapper<Brand>();
		queryWrapper.eq("brand_id", brandId);
		//根据主键查询出一条数据
		Brand brand = this.getOne(queryWrapper);
		//把删除位改为false 假删除
		brand.setDelFlag(false);
		boolean b =this.updateById(brand);
		if(!b) {
			throw new SystemException("删除失败");
		}
		return ResultInfo.success();
	}

	@Override
	public ResultInfo addBrand(Brand brand) {
		// TODO Auto-generated method stub
		//判断车辆品牌ID是否为空
		if(null != this.getById(brand.getBrandId())) {
			throw new SystemException("品牌ID已经存在，无法添加");
		}
		//判断车辆品牌不能为空，如果为空，则抛出异常
		if(!StringUtils.hasLength(brand.getBrandName())) {
			throw new SystemException("品牌名字不能为空");
		}
		brand.setDelFlag(true);
		this.save(brand);		
		return ResultInfo.success();
	}

}
